#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
  unsigned char ipbuf[sizeof(struct in_addr)];
  char buffer[256];
  int s, portno, sockfd, n, i;
  struct sockaddr_in serv_addr;

  //error checking
  if (argc!=3) {
    fprintf(stderr, "Usage: %s ip-address port-number\n", argv[0]);
    exit(EXIT_FAILURE);
  }

  //ip address string to ip address struct
  s = inet_pton(AF_INET, argv[1],ipbuf);

  //error checking
  if (s <= 0) {
    if (s == 0)
      fprintf(stderr, "IP Address not in presentation format");
    else
      perror("inet_pton");
    exit(EXIT_FAILURE);
  }

  //string to integer
  portno = atoi(argv[2]);

  //open socket
  sockfd = socket(AF_INET, SOCK_STREAM, 0);

  //error checking
  if (sockfd<0) {
    perror("socket");
    exit(EXIT_FAILURE);
  }

  //clear struct
  bzero((char*)&serv_addr, sizeof(serv_addr));

  //fill in data
  serv_addr.sin_family = AF_INET;
  
  //copy ip address
  bcopy(ipbuf, (char *)&serv_addr.sin_addr,sizeof(struct in_addr));
  
  //htons is for endianness
  serv_addr.sin_port = htons(portno);
  
  //connect
  if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) { 
    perror("connect");
    exit(EXIT_FAILURE);
  }

  for (i=0;i<4;i++) {
    char message[24];
    sprintf(message,"Command %d",i);
    n = write(sockfd,message,strlen(message));
    if (n < 0) { 
      perror("write");
      exit(EXIT_FAILURE);
    }
    printf("Message sent\n");
    sleep(1);
  }
  close(sockfd);
  exit(EXIT_SUCCESS);
}
